﻿using System;
using System.Text;
using System.Globalization;

namespace MvcApplication7
{
    public class MyStringWriter : System.IO.TextWriter
    {
        private readonly Func<StringBuilder> stringBuilderFunc;
        private static Encoding encoding;

        public MyStringWriter(Func<StringBuilder> stringBuilderFunc)
            : this(stringBuilderFunc, CultureInfo.CurrentCulture)
        {
        }

        public MyStringWriter(Func<StringBuilder> stringBuilderFunc, IFormatProvider formatProvider)
            : base(formatProvider)
        {
            this.stringBuilderFunc = stringBuilderFunc;
        }

        public override Encoding Encoding
        {
            get
            {
                if (encoding == null)
                {
                    encoding = new UnicodeEncoding(false, false);
                }
                return encoding;
            }
        }

        public virtual StringBuilder GetStringBuilder()
        {
            return stringBuilderFunc();
        }

        public override void Write(char value)
        {
            stringBuilderFunc().Append(value);
        }

        public override void Write(char[] buffer, int index, int count)
        {
            stringBuilderFunc().Append(buffer, index, count);
        }

        public override void Write(string value)
        {
            if (value != null) stringBuilderFunc().Append(value);
        }

        public override String ToString()
        {
            return stringBuilderFunc().ToString();
        }
    }
}
